package org.cypress.rtpack.controller;
//处理rtpack_moniip这个表的控制器

import org.cypress.rtpack.common.core.Result;
import org.cypress.rtpack.entity.RtpackMoniip;
import org.cypress.rtpack.service.IRtpackMoniipService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/rtpack_moniip")
public class RtpackMoniipController {

    @Autowired
    private IRtpackMoniipService rtpackMoniipService;

    private static final Logger logger = LoggerFactory.getLogger(RtpackMoniipController.class);

    @GetMapping("/by_index/{index}")
    public Result<RtpackMoniip> getByIndex(@PathVariable("index") Integer index) {
        RtpackMoniip inst = rtpackMoniipService.getByIndex(index);
        return Result.dataOf(inst);
    }

    @GetMapping("/list")
    public Result<RtpackMoniip> getList() {
        List<RtpackMoniip> list = rtpackMoniipService.getAll();
        return Result.dataOf(list);
    }

    @PutMapping("/updateByIndex")
    public Result<RtpackMoniip> updateConfig(@RequestBody RtpackMoniip moniip) {
        RtpackMoniip updatedConfig = rtpackMoniipService.updateByIndex(moniip);
        return Result.dataOf(updatedConfig);
    }

    @PutMapping("/batchUpdateByIndex")
    public Result<List<RtpackMoniip>> batchUpdate(@RequestBody List<RtpackMoniip> configList) {
        List<RtpackMoniip> updated = rtpackMoniipService.batchUpdateByIndex(configList);
        return Result.dataOf(updated);
    }

    /**
     * 删除原表并重新插入数据
     * @param newDataList 要插入的新数据列表
     * @return 操作结果（包含插入后的数据列表）
     */
    @PostMapping("/replaceAll")
    public Result<List<RtpackMoniip>> replaceAll(@RequestBody List<RtpackMoniip> newDataList) {
        try {
            // 1. 清空原表
            rtpackMoniipService.deleteAllRecords();

            // 2. 批量插入新数据
            List<RtpackMoniip> insertedList = rtpackMoniipService.batchInsert(newDataList);

            return Result.dataOf(insertedList);
        } catch (Exception e) {
            return new Result<>(Result.FAIL_CODE, "数据替换失败: " + e.getMessage());
        }
    }
}
